<template>
    <view>
        <!-- 表格 -->
        <view class="table">
            <view class="table-header">
                <view>日期</view>
                <view>设备</view>
                <view>密度</view>
                <view>检测员</view>
            </view>
            <view class="table-body" v-for="(row, index) in dataList" :key="index">
                <view>{{ row.date }}</view>
                <view @click="editData(index, 'morning')">{{ row.morning }}</view>
                <view @click="editData(index, 'noon')">{{ row.noon }}</view>
                <view @click="editData(index, 'evening')">{{ row.evening }}</view>
            </view>
        </view>

        <!-- 操作按钮 -->
        <view class="button-group">
            <button @click="showQueryDropdown">查询</button>
            <button @click="verifyAdminPassword">管理员登录</button>
            <button @click="goBack">返回</button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            dataList: [], // 存储多天的数据
            adminPassword: '123456', // 设置管理员密码
            queryDates: [] // 存储可查询的日期
        };
    },
    onLoad() {
        this.loadData();
        if (this.dataList.length === 0) {
            this.initDateData();
        }
        this.updateQueryDates();
    },
    methods: {
        // 从本地存储获取数据
        loadData() {
            try {
                const receivedData = uni.getStorageSync('dailyData');
                if (receivedData) {
                    if (typeof receivedData === 'string') {
                        this.dataList = JSON.parse(receivedData);
                    } else if (Array.isArray(receivedData)) {
                        this.dataList = receivedData;
                    } else {
                        console.error('本地存储的数据格式不正确');
                        this.dataList = [];
                    }
                }
            } catch (error) {
                console.error('解析数据时出错:', error);
                this.dataList = [];
            }
        },
        // 初始化日期数据
        initDateData() {
            const today = new Date();
            for (let i = 0; i < 1; i++) {
                const date = new Date(today);
                date.setDate(today.getDate() + i);
                const formattedDate = this.formatDate(date);
                this.dataList.push({
                    date: formattedDate,
                    morning: '测试数据',
                    noon: '测试数据',
                    evening: '检测员1'
                });
            }
        },
        // 格式化日期函数
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        editData(index, type) {
            uni.showModal({
                title: '编辑数据',
                content: '请输入新值',
                editable: true,
                success: (res) => {
                    if (res.confirm) {
                        const newValue = res.content;
                        if (['morning', 'noon', 'evening'].includes(type)) {
                            this.$set(this.dataList[index], type, newValue);
                            this.saveData();
                        }
                    }
                }
            });
        },
        // 保存数据到本地存储
        saveData() {
            try {
                uni.setStorageSync('dailyData', JSON.stringify(this.dataList));
            } catch (error) {
                console.error('保存数据时出错:', error);
            }
        },
        verifyAdminPassword() {
            uni.showModal({
                title: '管理员密码验证',
                content: '请输入管理员密码',
                editable: true,
                success: (res) => {
                    if (res.confirm) {
                        const inputPassword = res.content;
                        if (inputPassword === this.adminPassword) {
                            this.showAdminFunctions();
                        } else {
                            this.showToast('密码错误');
                        }
                    }
                }
            });
        },
        showAdminFunctions() {
            uni.showActionSheet({
                itemList: ['清除数据', '其他功能'],
                success: (res) => {
                    if (res.tapIndex === 0) {
                        this.confirmClearData();
                    } else if (res.tapIndex === 1) {
                        this.shareDataToWechat();
                    }
                },
                fail: (err) => {
                    console.error('显示操作菜单失败:', err);
                }
            });
        },
        confirmClearData() {
            uni.showModal({
                title: '确认清除',
                content: '确定要清除所有数据吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.clearData();
                    }
                }
            });
        },
        clearData() {
            try {
                uni.removeStorageSync('dailyData');
                this.dataList = [];
                this.updateQueryDates();
                this.showToast('数据已清除', 'success');
            } catch (error) {
                console.error('清除数据时出错:', error);
                this.showToast('清除数据失败');
            }
        },
        shareDataToWechat() {
            uni.showModal({
                title: '提示',
                content: '更多功能敬请期待',
                showCancel: false,
                confirmText: '确定'
            });
        },
        goBack() {
            uni.navigateTo({
                url: '/pages/index/index'
            });
        },
        // 显示提示信息
        showToast(title, icon = 'none', duration = 2000) {
            uni.showToast({
                title,
                icon,
                duration
            });
        },
        // 更新可查询的日期列表
        updateQueryDates() {
            this.queryDates = this.dataList.map(item => item.date);
        },
        // 显示查询下拉框
        showQueryDropdown() {
            if (this.queryDates.length === 0) {
                this.showToast('暂无可查询的日期');
                return;
            }
            uni.showActionSheet({
                itemList: this.queryDates,
                success: (res) => {
                    const selectedDate = this.queryDates[res.tapIndex];
                    this.showDataByDate(selectedDate);
                },
                fail: (err) => {
                    console.error('显示下拉框失败:', err);
                }
            });
        },
        // 显示指定日期的数据信息
showDataByDate(date) {
    // 筛选出该日期的所有数据
    const filteredData = this.dataList.filter(item => item.date === date);
    if (filteredData.length > 0) {
        let content = '';
        // 遍历筛选后的数据，拼接每条数据的信息
        filteredData.forEach((row, index) => {
            content += `数据 ${index + 1}:\n日期: ${row.date}\n设备: ${row.morning}\n密度数据: ${row.noon}\n检测员: ${row.evening}\n\n`;
        });
        // 去除最后多余的换行符
        content = content.trim();
        uni.showModal({
            title: '数据信息',
            content,
            showCancel: false
        });
    } else {
        this.showToast('未找到该日期的数据');
    }
}
    }
};
</script>

<style scoped>
.table {
    border: 1px solid #ccc;
    border-collapse: collapse;
}

.table-header {
    display: flex;
    background-color: #f0f0f0;
}

.table-header view {
    flex: 1;
    padding: 10px;
    border-bottom: 1px solid #ccc;
    border-right: 1px solid #ccc;
}

.table-body {
    display: flex;
    border-bottom: 1px solid #ccc;
}

.table-body view {
    flex: 1;
    padding: 10px;
    border-right: 1px solid #ccc;
}

.button-group {
    margin-top: 20px;
}

.button-group button {
    margin-right: 10px;
}
</style>